package com.example.config;

import com.alibaba.fastjson.JSON;
import com.example.entity.SysUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RedirectAuthentication implements AuthenticationSuccessHandler {
    private final String forwardUrl;

    public RedirectAuthentication(String forwardUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> {
            return "'" + forwardUrl + "' is not a valid forward URL";
        });
        this.forwardUrl = forwardUrl;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
//        User user = (User)authentication.getPrincipal();
//        response.getWriter().print(JSON.toJSON(user));
//        response.getWriter().flush();
//        response.getWriter().close();
        request.getRequestDispatcher(this.forwardUrl).forward(request,response);
    }



    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        User user = (User)authentication.getPrincipal();
//        response.getWriter().print(JSON.toJSON(user));
//        response.getWriter().flush();
//        response.getWriter().close();
        response.sendRedirect(this.forwardUrl);
    }
}
